/**
 * 景区管理页面
 * 整合景区数据管理、3D地图查看、AI助手等功能
 */

'use client'

import React, { useState, useRef } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { toast } from 'sonner'
import { Map, Database, Bot, Eye, EyeOff, Settings } from 'lucide-react'

// 组件导入
import { AttractionManagementPanel } from '@/components/attraction/AttractionManagementPanel'
import { AttractionMapViewer, AttractionMapViewerRef } from '@/components/attraction/AttractionMapViewer'
import { AttractionAIAssistant } from '@/components/attraction/AttractionAIAssistant'

export default function AttractionManagementPage() {
  const [selectedAttraction, setSelectedAttraction] = useState<any>(null)
  const [showDataPanel, setShowDataPanel] = useState(true)
  const [showAIAssistant, setShowAIAssistant] = useState(true)
  const mapViewerRef = useRef<AttractionMapViewerRef>(null)

  // 处理景区选择
  const handleAttractionSelect = (attraction: any) => {
    setSelectedAttraction(attraction)
    if (attraction) {
      toast.success(`已切换到景区: ${attraction.name}`)
      // 地图飞行到景区中心
      mapViewerRef.current?.flyTo(attraction.center, 16)
    }
  }

  // 处理模型刷新
  const handleRefreshModel = (attractionId: string) => {
    toast.success('正在刷新3D模型...')
    mapViewerRef.current?.refreshModel()
    mapViewerRef.current?.refreshStores()
    mapViewerRef.current?.refreshFacilities()
  }

  // 处理数据变更
  const handleDataChange = () => {
    // 刷新地图上的标记
    mapViewerRef.current?.refreshStores()
    mapViewerRef.current?.refreshFacilities()
  }

  // AI助手导航回调
  const handleAINavigation = (location: { lng: number; lat: number }) => {
    mapViewerRef.current?.flyTo([location.lng, location.lat], 18)
    toast.success('正在为您导航...')
  }

  // AI助手商铺选择回调
  const handleAIStoreSelect = (store: any) => {
    toast.success(`已选择商铺: ${store.name}`)
    if (store.position) {
      mapViewerRef.current?.flyTo(store.position, 18)
    }
  }

  return (
    <div className="h-screen bg-gray-50 flex flex-col overflow-hidden">
      {/* 页面头部 */}
      <div className="bg-white border-b px-6 py-4 flex-shrink-0">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
              <Map className="w-6 h-6 text-blue-600" />
              景区数字孪生管理平台
            </h1>
            <p className="text-gray-600 mt-1">集成3D地图、数据绑定、AI导游的全功能管理系统</p>
          </div>
          
          <div className="flex items-center gap-2">
            {selectedAttraction && (
              <Badge variant="secondary" className="px-3 py-1">
                当前景区: {selectedAttraction.name}
              </Badge>
            )}
            
            <Button
              variant="outline"
              size="sm"
              onClick={() => setShowDataPanel(!showDataPanel)}
              className="gap-1"
            >
              <Database className="w-4 h-4" />
              {showDataPanel ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
              数据面板
            </Button>
            
            <Button
              variant="outline"
              size="sm"
              onClick={() => setShowAIAssistant(!showAIAssistant)}
              className="gap-1"
            >
              <Bot className="w-4 h-4" />
              {showAIAssistant ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
              AI助手
            </Button>
          </div>
        </div>
      </div>

      {/* 主要内容区域 */}
      <div className="flex-1 flex overflow-hidden">
        {/* 左侧数据管理面板 */}
        {showDataPanel && (
          <div className="w-96 bg-white border-r flex-shrink-0 overflow-hidden">
            <div className="h-full overflow-y-auto">
              <AttractionManagementPanel
                className="p-4"
                onAttractionSelect={handleAttractionSelect}
                onRefreshModel={handleRefreshModel}
              />
            </div>
          </div>
        )}

        {/* 中间3D地图区域 */}
        <div className="flex-1 relative overflow-hidden">
          {selectedAttraction ? (
            <AttractionMapViewer
              ref={mapViewerRef}
              attraction={selectedAttraction}
              className="w-full h-full"
              onDataChange={handleDataChange}
            />
          ) : (
            <div className="flex items-center justify-center h-full bg-gray-100">
              <Card className="w-96">
                <CardHeader className="text-center">
                  <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <Map className="w-8 h-8 text-blue-600" />
                  </div>
                  <CardTitle>欢迎使用景区数字孪生系统</CardTitle>
                </CardHeader>
                <CardContent className="text-center space-y-4">
                  <p className="text-gray-600">
                    请在左侧数据面板中选择或创建一个景区开始使用
                  </p>
                  
                  <div className="grid grid-cols-2 gap-3 text-sm">
                    <div className="p-3 bg-blue-50 rounded-lg">
                      <div className="font-medium text-blue-900">🗺️ 3D地图</div>
                      <div className="text-blue-700 mt-1">高德地图+Three.js</div>
                    </div>
                    <div className="p-3 bg-green-50 rounded-lg">
                      <div className="font-medium text-green-900">🏪 数据绑定</div>
                      <div className="text-green-700 mt-1">商铺+设施管理</div>
                    </div>
                    <div className="p-3 bg-purple-50 rounded-lg">
                      <div className="font-medium text-purple-900">🤖 AI助手</div>
                      <div className="text-purple-700 mt-1">智能导游+商业BOT</div>
                    </div>
                    <div className="p-3 bg-orange-50 rounded-lg">
                      <div className="font-medium text-orange-900">💾 本地存储</div>
                      <div className="text-orange-700 mt-1">IndexedDB数据库</div>
                    </div>
                  </div>
                  
                  <div className="pt-4 border-t">
                    <p className="text-xs text-gray-500">
                      💡 点击建筑绑定商铺，点击地面绑定设施
                    </p>
                  </div>
                </CardContent>
              </Card>
            </div>
          )}

          {/* 地图控制器 */}
          {selectedAttraction && (
            <div className="absolute top-4 left-4 space-y-2">
              <Card className="p-3">
                <div className="text-sm font-medium text-gray-700 mb-2">
                  🎮 操作指南
                </div>
                <div className="text-xs text-gray-600 space-y-1">
                  <div>• 点击建筑物：绑定商铺信息</div>
                  <div>• 点击地面：绑定设施信息</div>
                  <div>• 拖拽：移动地图视角</div>
                  <div>• 滚轮：缩放地图</div>
                </div>
              </Card>

              <Card className="p-3">
                <div className="text-sm font-medium text-gray-700 mb-2">
                  📊 当前景区
                </div>
                <div className="text-xs text-gray-600 space-y-1">
                  <div>📍 {selectedAttraction.name}</div>
                  <div>🌐 {selectedAttraction.center[0].toFixed(4)}, {selectedAttraction.center[1].toFixed(4)}</div>
                  <div>🏗️ {selectedAttraction.modelPath}</div>
                </div>
              </Card>
            </div>
          )}
        </div>
      </div>

      {/* AI助手浮窗 */}
      {showAIAssistant && selectedAttraction && (
        <AttractionAIAssistant
          attractionId={selectedAttraction.id}
          onNavigateTo={handleAINavigation}
          onStoreSelect={handleAIStoreSelect}
        />
      )}

      {/* AI数据分析面板 */}
      {selectedAttraction && (
        <div className="fixed top-4 left-4 w-72 bg-white rounded-lg shadow-lg border z-30">
          <div className="p-3 border-b bg-gradient-to-r from-purple-50 to-pink-50">
            <div className="flex items-center gap-2">
              <span className="text-lg">🤖</span>
              <div>
                <h3 className="font-semibold text-sm">AI景区分析</h3>
                <p className="text-xs text-gray-600">{selectedAttraction.name}</p>
              </div>
            </div>
          </div>
          
          <div className="p-3 space-y-3">
            {/* 实时AI分析 */}
            <div className="space-y-2">
              <h4 className="text-xs font-medium text-gray-800">🎯 智能分析结果</h4>
              
              <div className="text-xs space-y-1">
                <div className="flex justify-between">
                  <span className="text-gray-600">游客流量预测</span>
                  <span className="text-green-600 font-medium">↑ 预计增长15%</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">热门设施预测</span>
                  <span className="text-blue-600 font-medium">3个高人气区域</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">商业机会评估</span>
                  <span className="text-purple-600 font-medium">5个潜在位置</span>
                </div>
              </div>
            </div>

            {/* AI推荐 */}
            <div className="p-2 bg-blue-50 rounded border-l-4 border-blue-400">
              <p className="text-xs font-medium text-blue-900 mb-1">💡 AI建议</p>
              <p className="text-xs text-blue-700">
                建议在游客中心附近增设2个便民设施，预计可提升游客满意度12%
              </p>
            </div>

            {/* 快捷功能 */}
            <div className="grid grid-cols-2 gap-1.5">
              <Button 
                size="sm" 
                variant="outline" 
                className="text-xs h-8"
                onClick={() => toast.success('正在生成游客流量报告...')}
              >
                📊 流量分析
              </Button>
              <Button 
                size="sm" 
                variant="outline" 
                className="text-xs h-8"
                onClick={() => toast.success('正在优化商铺布局...')}
              >
                🏪 布局优化
              </Button>
              <Button 
                size="sm" 
                variant="outline" 
                className="text-xs h-8"
                onClick={() => toast.success('正在预测设施需求...')}
              >
                🎯 需求预测
              </Button>
              <Button 
                size="sm" 
                variant="outline" 
                className="text-xs h-8"
                onClick={() => toast.success('正在启动智能推荐...')}
              >
                🤖 智能推荐
              </Button>
            </div>

            {/* AI学习状态 */}
            <div className="text-xs text-gray-500 border-t pt-2">
              <div className="flex items-center justify-between">
                <span>AI模型准确率</span>
                <span className="text-green-600 font-medium">94.5%</span>
              </div>
              <div className="flex items-center justify-between">
                <span>数据更新</span>
                <span>3分钟前</span>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 功能状态指示器 */}
      <div className="fixed bottom-4 left-4 flex flex-col gap-2">
        <div className="flex items-center gap-2 bg-white rounded-lg p-2 shadow-sm border text-xs">
          <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
          <span className="text-gray-600">系统运行正常</span>
        </div>
        
        {selectedAttraction && (
          <div className="flex items-center gap-2 bg-white rounded-lg p-2 shadow-sm border text-xs">
            <div className="w-2 h-2 bg-blue-500 rounded-full" />
            <span className="text-gray-600">景区数据已加载</span>
          </div>
        )}
      </div>
    </div>
  )
}